﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Mapster;
using Masuit.Tools.Files;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using XREditor.Dtos;
using XREditor.Models;

namespace XREditor.Controllers
{
    /// <summary>
    /// 项目管理
    /// </summary>
    [DynamicApiController]
    public class ProjectController
    {
        private readonly ILogger<ProjectController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private readonly ISevenZipCompressor _sevenZipCompressor;
        public ProjectController(ISqlSugarClient sqlSugarClient, ISevenZipCompressor sevenZipCompressor)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
            _sevenZipCompressor = sevenZipCompressor;
        }

        /// <summary>
        /// 项目列表
        /// </summary>
        /// <param name="ulsfd">参照下方Schemas中：ProjectSearchListFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] ProjectSearchListFormDto pslfd)
        {
            RefAsync<int> total = 0;
            List<Project> projects = await db.Queryable<Project>()
                .Where(mx => mx.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(pslfd.Content), mx => mx.Name.Contains(pslfd.Content))
                .ToPageListAsync(pslfd.PageIndex, pslfd.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = projects,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加项目
        /// </summary>
        /// <param name="uifd">参照下方Schemas中：ProjectInfoFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] ProjectInfoFormDto pifd)
        {
            long id = await db.Insertable<Project>(pifd.Adapt<Project>()).ExecuteReturnBigIdentityAsync();

            // 创建一个时间戳目录
            string projectPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "project", $"p_{id}");
            Directory.CreateDirectory(projectPath);

            if (!string.IsNullOrEmpty(pifd.Path)) { 
                
                _sevenZipCompressor.Decompress(Path.Combine(App.WebHostEnvironment.WebRootPath, pifd.Path.Substring(1)), projectPath);

                // 更新Url
                await db.Updateable<Project>()
                    .SetColumns(p => p.Url == $"/project/p_{id}/")
                    .Where(p => p.Id == id)
                    .ExecuteCommandAsync();
            }
            

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = await db.Queryable<Project>().InSingleAsync(id),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="pfd">参照下方Schemas中：PrimaryFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] PrimaryFormDto pfd) {
            await db.Updateable<Project>().SetColumns(mx => mx.IsActive == 0).Where(mx => mx.Id == pfd.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改项目
        /// </summary>
        /// <param name="uifd">参照下方Schemas中：ProjectInfoFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] ProjectInfoFormDto pifd) {
            await db.Updateable<Project>(pifd.Adapt<Project>()).ExecuteCommandAsync();

            if (!string.IsNullOrEmpty(pifd.Path))
            {
                string projectPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "project", $"p_{pifd.Id}");

                _sevenZipCompressor.Decompress(Path.Combine(App.WebHostEnvironment.WebRootPath, pifd.Path.Substring(1)), projectPath);

                // 更新Url
                await db.Updateable<Project>()
                    .SetColumns(p => p.Url == $"/project/p_{pifd.Id}/")
                    .Where(p => p.Id == pifd.Id)
                    .ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = await db.Queryable<Project>().InSingleAsync(pifd.Id),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看项目
        /// </summary>
        /// <param name="pfd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] PrimaryFormDto pfd) {
            Project project = await db.Queryable<Project>()
                .InSingleAsync(pfd.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = project,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

    }
}
